<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Story
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */


class Story_IndexController extends Core_Controller_Action_Standard
{
	protected $_navigation;

	public function init()
	{
		if (!$this->_helper->requireAuth()->setAuthParams('story', null, 'view')->
				isValid())
			return;

		if (!Engine_Api::_()->core()->hasSubject()) {
			if (0 !== ($story_id = (int)$this->_getParam('story_id')) && null !== ($story =
					Engine_Api::_()->getItem('story', $story_id))) {
				Engine_Api::_()->core()->setSubject($story);
			}
		}

		$this->_helper->requireUser->addActionRequires(array(
				'create',
				'delete',
				'edit',
				'manage',
				'success',
				'publish'));

		$this->_helper->requireSubject->setActionRequireTypes(array(
				'delete' => 'story',
				'edit' => 'story',
				'success' => 'story',
				'publish' => 'story',
				'view' => 'story',
		));

	}

	public function indexAction()
	{
		$this->_helper->content->setNoRender()->setEnabled();
	}

	// NONE USER SPECIFIC METHODS
	public function browseAction()
	{
		$this->_helper->content->setNoRender()->setEnabled();
		return;
	}


	public function manageAction()
	{
		$this->_helper->content->setNoRender()->setEnabled();
		return;

		$viewer = Engine_Api::_()->user()->getViewer();
		$this->_loadNavigations();


		$this->view->allowed_upload = Engine_Api::_()->authorization()->getPermission($viewer->
				level_id, 'story', 'photo');

		$this->view->approval = $approval = (int)Engine_Api::_()->authorization()->
		getPermission($viewer->level_id, 'story', 'approval');


		$this->view->form = $form = new Story_Form_Search();
		$form->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble(array
				(), 'story_manage', true));

		$values = array();
		// Populate form data
		if ($form->isValid($this->_getAllParams())) {
			$values = $form->getValues();
		}

		$values = Engine_Api::_()->getApi('filter', 'radcodes')->removeKeyEmptyValues($values);
		$this->view->formValues = $values;

		$this->view->assign($values);

		// items needed to show what is being filtered in browse page
		if (!empty($values['category'])) {
			$this->view->categoryObject = Engine_Api::_()->story()->getCategory($values['category']);
		}
		if (!empty($values['tag'])) {
			$this->view->tagObject = Engine_Api::_()->getItem('core_tag', $values['tag']);
		}

		$values['user'] = $viewer;
		$values['limit'] = (int)Engine_Api::_()->getApi('settings', 'core')->getSetting('story.page',
				10);

		// Get paginator
		$this->view->paginator = $paginator = Engine_Api::_()->story()->
		getStoriesPaginator($values);
		$paginator->setCurrentPageNumber($this->_getParam('page', 1));

		$this->view->can_create = Engine_Api::_()->authorization()->isAllowed('story', $viewer,
				'create');
	}


	public function viewAction()
	{
		$this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
		$this->view->story = $story = Engine_Api::_()->core()->getSubject('story');

		//return $this->_forward('requireauth', 'error', 'core');
		// require log in --- and -- not logged in => show log in screen
		if (!Engine_Api::_()->getApi('settings', 'core')->getSetting('story.public', 1) &&
				!$this->_helper->requireUser()->isValid()) {
			return;
		}

		// logged in && no view permission => show no permission
		if ($this->_helper->requireUser()->checkRequire() && !$this->_helper->
				requireAuth()->setAuthParams($story, null, 'view')->isValid()) {
			return;
		} else
			if (!$this->_helper->requireUser()->checkRequire()) {
			if (!$this->_helper->requireAuth()->setAuthParams($story, null, 'view')->
					checkRequire()) {
				return $this->_forward('requireuser', 'error', 'core');
			}
		}
		//if (!$this->_helper->requireAuth()->setAuthParams($story, null, 'view')->checkRequire()) {
		//  return $this->_forward('requireauth', 'error', 'core');
		// }


		$this->view->owner = $owner = Engine_Api::_()->user()->getUser($story->owner_id);

		$this->view->canEdit = $this->_helper->requireAuth()->setAuthParams($story, null,
				'edit')->checkRequire();
		$this->view->canUpload = $this->_helper->requireAuth()->setAuthParams($story, null,
				'photo')->checkRequire();
		$this->view->canDelete = $this->_helper->requireAuth()->setAuthParams($story, null,
				'delete')->checkRequire();
		$this->view->canPublish = $story->isOwner($viewer) && !$story->isPublished();

		$this->view->approval = 0;
		if ($viewer->getIdentity()) {
			$this->view->approval = (int)Engine_Api::_()->authorization()->getPermission($viewer->
					level_id, 'story', 'approval');
		}
		$archiveList = Engine_Api::_()->story()->getArchiveList(array('user_id' => $story->
				owner_id, 'published' => 1));

		$story->view_count++;
		$story->save();

		$this->view->story = $story;
		if ($story->photo_id) {
			$this->view->main_photo = $story->getPhoto($story->photo_id);
		}
		// get tags
		$this->view->storyTags = $story->tags()->getTagMaps();
		$this->view->userTags = $story->tags()->getTagsByTagger($story->getOwner());

		// get archive list
		$this->view->archive_list = $this->handleArchiveList($archiveList);

		$view = $this->view;
		$view->addHelperPath(APPLICATION_PATH .
				'/application/modules/Fields/View/Helper', 'Fields_View_Helper');
		$this->view->fieldStructure = $fieldStructure = Engine_Api::_()->fields()->
		getFieldsStructurePartial($story);

		// album material
		$this->view->album = $album = $story->getSingletonAlbum();
		$this->view->paginator = $paginator = $album->getCollectiblesPaginator();
		$paginator->setCurrentPageNumber($this->_getParam('page', 1));
		$paginator->setItemCountPerPage(Engine_Api::_()->getApi('settings', 'core')->
				getSetting('story.gallery', 4));

		if ($story->category_id != 0)
			$this->view->category = Engine_Api::_()->story()->getCategory($story->
					category_id);
		$this->view->userCategories = Engine_Api::_()->story()->getUserCategories($this->
				view->story->owner_id);

		// related stories
		$this->view->relatedStories = Engine_Api::_()->story()->getRelatedStories($story);
	}


	public function createAction()
	{
		//if( !$this->_helper->requireUser()->isValid() ) return;
		if (!$this->_helper->requireAuth()->setAuthParams('story', null, 'create')->
				isValid())
			return;
		$viewer = Engine_Api::_()->user()->getViewer();

		//Load en4.story prototype
		$this->view->headScript()->appendFile(Zend_Registry::get('StaticBaseUrl')
				. 'application/modules/Story/externals/scripts/core.js');
		
		$this->view->headScript()->appendFile(Zend_Registry::get('StaticBaseUrl')
				. 'application/modules/Story/externals/scripts/file.js');
		
		$this->view->headScript()->appendFile(Zend_Registry::get('StaticBaseUrl')
				. 'externals/tinymce/tiny_mce.js');
		
		$subject = null;
		if( !Engine_Api::_()->core()->hasSubject() )
		{
			$id = $this->_getParam('story_id');
			if( null !== $id )
			{
				$subject = Engine_Api::_()->getItem('story', $id);
				if( $subject && $subject->getIdentity()){
					//Check Owner
					if(!$subject->isOwner($viewer)){
						return $this->_forward('requireauth', 'error', 'core');
					}					
					
					Engine_Api::_()->core()->setSubject($subject);
				}
			}
		}
		
		$this->_helper->content->setNoRender()->setEnabled();
		return;
	}

	public function editAction()
	{
		//if( !$this->_helper->requireUser()->isValid() ) return;

		$viewer = Engine_Api::_()->user()->getViewer();
		$this->view->story = $story = Engine_Api::_()->core()->getSubject('story');

		if (!$this->_helper->requireAuth()->setAuthParams($story, null, 'edit')->
				isValid()) {
			return $this->_forward('requireauth', 'error', 'core');
		}

		// Get navigation
		$navigation = $this->getNavigation();
		$this->view->navigation = $navigation;

		$this->view->form = $form = new Story_Form_Edit(array('item' => $story));

		// only for create
		$form->removeElement('photo');

		$form->populate($story->toArray());

		$auth = Engine_Api::_()->authorization()->context;
		$roles = array(
				'owner',
				'owner_member',
				'owner_member_member',
				'owner_network',
				'registered',
				'everyone');
		$auth_keys = array(
				'view' => 'everyone',
				'comment' => 'registered',
		);

		// Save story entry
		if (!$this->getRequest()->isPost()) {

			// prepare tags
			$storyTags = $story->tags()->getTagMaps();

			$tagString = '';
			foreach ($storyTags as $tagmap) {
				if ($tagString !== '')
					$tagString .= ', ';
				$tagString .= $tagmap->getTag()->getTitle();
			}

			$this->view->tagNamePrepared = $tagString;
			$form->tags->setValue($tagString);

			foreach ($auth_keys as $auth_key => $auth_default) {
				$auth_field = 'auth_' . $auth_key;

				foreach ($roles as $i => $role) {
					if (isset($form->$auth_field->options[$role]) && 1 === $auth->isAllowed($story,
							$role, $auth_key)) {
						$form->$auth_field->setValue($role);
					}
				}
			}

			if ($story->isPublished())
				$form->removeElement('published');

			return;
		}
		if (!$form->isValid($this->getRequest()->getPost())) {
			return;
		}


		// Process

		// handle save for tags
		$values = $form->getValues();
		$tags = preg_split('/[,]+/', $values['tags']);
		$tags = array_filter(array_map("trim", $tags));

		$db = Engine_Db_Table::getDefaultAdapter();
		$db->beginTransaction();
		try {
			$story->setFromArray($values);
			$story->modified_date = date('Y-m-d H:i:s');

			$story->tags()->setTagMaps($viewer, $tags);
			$story->save();

			// Save custom fields
			$customfieldform = $form->getSubForm('customField');
			$customfieldform->setItem($story);
			$customfieldform->saveValues();

			// CREATE AUTH STUFF HERE
			$values = $form->getValues();

			// CREATE AUTH STUFF HERE
			foreach ($auth_keys as $auth_key => $auth_default) {
				$auth_value = isset($values['auth_' . $auth_key]) ? $values['auth_' . $auth_key] :
				$auth_default;
				$authMax = array_search($auth_value, $roles);

				foreach ($roles as $i => $role) {
					$auth->setAllowed($story, $role, $auth_key, ($i <= $authMax));
				}
			}

			// Add activity only if story is published
			$action = Engine_Api::_()->getDbtable('actions', 'activity')->
			getActionsByObject($story);
			if (count($action->toArray()) <= 0 && $story->isPublished()) {

				if ($viewer->getIdentity() != $story->owner_id) {
					$owner = Engine_Api::_()->user()->getUser($story->owner_id);
				} else {
					$owner = $viewer;
				}

				$action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($owner,
						$story, 'story_new');
				if ($action != null) {
					Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $story);
				}
			}

			// Rebuild privacy
			$actionTable = Engine_Api::_()->getDbtable('actions', 'activity');
			foreach ($actionTable->getActionsByObject($story) as $action) {
				$actionTable->resetActivityBindings($action);
			}
			$db->commit();


			$savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Your changes were saved.");
			$form->addNotice($savedChangesNotice);
			$customfieldform->removeElement('submit');

		}
		catch (exception $e) {
			$db->rollBack();
			throw $e;
		}
	}


	public function deleteAction()
	{
		$viewer = Engine_Api::_()->user()->getViewer();
		$this->view->story = $story = Engine_Api::_()->core()->getSubject('story');

		//if( $viewer->getIdentity() != $story->owner_id && !$this->_helper->requireAuth()->setAuthParams($story, null, 'edit')->isValid())
		if (!$this->_helper->requireAuth()->setAuthParams($story, null, 'delete')->
				isValid())
			return;

		// Get navigation
		$navigation = $this->getNavigation();
		$this->view->navigation = $navigation;

		if ($this->getRequest()->isPost() && $this->getRequest()->getPost('confirm') == true) {
			$story_id = $story->story_id;
			$table = Engine_Api::_()->getDbTable('notifications', "activity");
            $table->removeNotificationsByObjectId($story_id);
            $table = Engine_Api::_()->getDbTable('follow', "story");
            $table->deleteFollow($story_id);
            $table = Engine_Api::_()->getDbTable('membership', "story");
            $table->deleteMembership($story_id);
			$this->view->story->delete();
			return $this->_helper->redirector->gotoRoute(array(), 'story_manage', true);
		}
	}


	public function publishAction()
	{
		$viewer = Engine_Api::_()->user()->getViewer();
		$this->view->story = $story = Engine_Api::_()->core()->getSubject('story');

		// only owner can publish
		if ($viewer->getIdentity() != $story->owner_id) {
			return $this->_forward('requireauth', 'error', 'core');
		}

		$approval = (int)Engine_Api::_()->authorization()->getPermission($viewer->
				level_id, 'story', 'approval');
		if ($approval) {
			return $this->_forward('requireauth', 'error', 'core');
		}

		if ($story->isPublished()) {
			return $this->_helper->redirector->gotoRoute(array(), 'story_manage', true);
		}


		$table = $story->getTable();
		$db = $table->getAdapter();
		$db->beginTransaction();

		try {
			$story->published = 1;
			$story->save();

			// Add activity only if story is published
			if ($story->isPublished()) {
				$action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer,
						$story, 'story_new');
				if ($action != null) {
					Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $story);
				}
			}

			$db->commit();

		}

		catch (exception $e) {
			$db->rollBack();
			throw $e;
		}

		return $this->_redirectCustom($story);
		//return $this->_helper->redirector->gotoRoute(array(), 'story_manage', true);
	}

	public function successAction()
	{
		$viewer = Engine_Api::_()->user()->getViewer();
		$this->view->story = $story = Engine_Api::_()->core()->getSubject('story');

		if ($viewer->getIdentity() != $story->owner_id) {
			return $this->_forward('requireauth', 'error', 'core');
		}

		$this->_loadNavigations();

		if ($this->getRequest()->isPost() && $this->getRequest()->getPost('confirm') == true) {
			return $this->_helper->redirector->gotoRoute(array(
					'controller' => 'photo',
					'action' => 'upload',
					'subject' => $story->getGuid()), 'story_extended', true);
		}
	}


	public function tagsAction()
	{
		$this->_helper->content->setNoRender()->setEnabled();
		return;
		/*
		 * $viewer = Engine_Api::_()->user()->getViewer();
		* $this->view->form = $form = new Story_Form_Search();
		*
		* if( !$viewer->getIdentity() )
			* {
		* $form->removeElement('show');
		* }
		*
		* $this->_loadNavigations();
		* $this->view->can_create = $this->_helper->requireAuth()->setAuthParams('story', null, 'create')->checkRequire();
		*
		* $this->view->tags = $tags = Engine_Api::_()->story()->getPopularTags(array('limit' => 999, 'order' => 'text'));
		*/
	}

	public function getNavigation($active = false)
	{
		if (is_null($this->_navigation)) {
			$this->_navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('story_main');
		}
		return $this->_navigation;
	}

	protected function _loadNavigations()
	{
		// Get navigation
		$this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')->
		getNavigation('story_main');

		// Get quick navigation
		$this->view->quickNavigation = $quickNavigation = Engine_Api::_()->getApi('menus',
				'core')->getNavigation('story_quick');
	}

	public function handleArchiveList($results)
	{
		$archive_list = array();

		foreach ($results as $result) {
			$story_date = strtotime($result['period']);

			$date_info = Radcodes_Lib_Helper_Date::archive($story_date);
			$date_start = $date_info['date_start'];

			if (!isset($archive_list[$date_start])) {
				$archive_list[$date_start] = $date_info;
				$archive_list[$date_start]['count'] = $result['total'];
			} else {
				$archive_list[$date_start]['count'] += $result['total'];
			}
		}

		return $archive_list;
	}


	public function uploadPhotoAction()
	{
		$viewer = Engine_Api::_()->user()->getViewer();

		$this->_helper->layout->disableLayout();

		if (!Engine_Api::_()->authorization()->isAllowed('album', $viewer, 'create')) {
			return false;
		}

		if (!$this->_helper->requireAuth()->setAuthParams('album', null, 'create')->
				isValid())
			return;

		if (!$this->_helper->requireUser()->checkRequire()) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Max file size limit exceeded (probably).');
			return;
		}

		if (!$this->getRequest()->isPost()) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
			return;
		}
		if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name'])) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid Upload');
			return;
		}

		$db = Engine_Api::_()->getDbtable('photos', 'album')->getAdapter();
		$db->beginTransaction();

		try {
			$viewer = Engine_Api::_()->user()->getViewer();

			$album = Engine_Api::_()->story()->getSpecialAlbum($viewer, 'story');

			$photoTable = Engine_Api::_()->getDbtable('photos', 'album');
			$photo = $photoTable->createRow();
			$photo->setFromArray(array(
					'owner_type' => 'user',
					'owner_id' => $viewer->getIdentity(),
					'collection_id' => $album->album_id, // for SE <= 4.1.6 .. (this column was removed since v4.1.7
					'album_id' => $album->album_id, // for SE >= v4.1.7
			));
			$photo->save();

			$photo->setPhoto($_FILES['Filedata']);

			$this->view->status = true;
			$this->view->name = $_FILES['Filedata']['name'];
			$this->view->photo_id = $photo->photo_id;
			$this->view->photo_url = $photo->getPhotoUrl();

			if (!$album->photo_id) {
				$album->photo_id = $photo->getIdentity();
				$album->save();
			}

			$auth = Engine_Api::_()->authorization()->context;
			$auth->setAllowed($photo, 'everyone', 'view', true);
			$auth->setAllowed($photo, 'everyone', 'comment', true);
			$auth->setAllowed($album, 'everyone', 'view', true);
			$auth->setAllowed($album, 'everyone', 'comment', true);


			$db->commit();

		}
		catch (Album_Model_Exception $e) {
			$db->rollBack();
			$this->view->status = false;
			$this->view->error = $this->view->translate($e->getMessage());
			//throw $e;
			return;

		}
		catch (exception $e) {
			$db->rollBack();
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('An error occurred.');
			throw $e;
			return;
		}
	}

	/**
	 * Handle submit creating new story
	 */
	public function createexAction()
	{
		//Check Valid User logged in
		if (!$this->_helper->requireAuth()->setAuthParams('story', null, 'create')->isValid()){
			return;
		}
		
		
		
		$viewer = Engine_Api::_()->user()->getViewer();
			
		$form = new Story_Form_Create_Custom(array(
				'category' => Story_Model_Category::SHORT_STORY,
				'tit' => 'Short Story',
		));
			
		if ($this->getRequest()->isPost()) {
			$table = Engine_Api::_()->getItemTable('story');
			$db = $table->getAdapter();
			$db->beginTransaction();
			$uploading_photo = false;

			try {
				$featured = Engine_Api::_()->authorization()->getPermission($viewer->level_id,
						'story', 'featured') ? 1 : 0;
				$sponsored = Engine_Api::_()->authorization()->getPermission($viewer->level_id,
						'story', 'sponsored') ? 1 : 0;
					
				// Create story
				$values = array_merge($_POST, array(
						'owner_type' => $viewer->getType(),
						'owner_id' => $viewer->getIdentity(),
						'featured' => $featured,
						'sponsored' => $sponsored,
				));

				if(isset($values['story_id']) && !empty($values['story_id'])){
					$story = Engine_Api::_()->getItem('story', $values['story_id']);
					// Person 2 edit story
					$values['owner_id'] = $story->owner_id;
				} else {
					$story = $table->createRow();
				}
				if(isset($values['story_id'])){
					unset($values['story_id']);
				}

				$story->setFromArray($values);
				$body = 'body_' . $values['category_id'];
				if(!isset($values[$body])){
					$values[$body] = "";
				}
				//Set body
				if($values[$body] == null){
					$values[$body] = "";
				}
				$story->body = $values[$body];
				
				//Update selected_date
				$selected_date = "selected_date_" . $values['category_id'];
				if(isset($values[$selected_date]))	{					
					$oldTz = date_default_timezone_get();
				    date_default_timezone_set($viewer->timezone);				    
				    $start_date = strtotime(implode(" ", $values[$selected_date]));
				    //echo $start_date;
				    date_default_timezone_set($oldTz);
				    $tmp = date('Y-m-d H:i:s', $start_date);
					$story->selected_date = $tmp;
				}
				
				//echo "<pre>". print_r($_FILES, true)."</pre>";
				//die();
				
				if(isset($values['publish'])){
					$story->published = 1;	
					if($story->owner_id==$viewer->getIdentity())
						$story->invite_request = 2;
					else $story->invite_request = 1;
				}
				if(isset($values['submit'])){
					if($story->owner_id==$viewer->getIdentity())
						$story->invite_request = 2;
					else $story->invite_request = 1;
				}
				if(isset($values['save'])){
					if($story->owner_id==$viewer->getIdentity())
						$story->invite_request = 1;
					else $story->invite_request = 2;
				}
				if($values['story_category']){
					$story->category_id = $values['story_category'];
				}

				$story->save();
				
				// Add notification
				$notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
				$table = Engine_Api::_()->getDbTable("follow", "story");
          		$all_follow = $table->getAllFollow();
          		$resource_follow = array();
          		foreach($all_follow as $row){
          			$result_story = Engine_Api::_()->getItem('story', $row->resource_id);
					if(!$result_story) continue;
					if($result_story->category_id==$story->category_id){
						$resource_follow[]= $row->resource_id;
					}
          		}
          		$sent_follow = array();
          		foreach($resource_follow as $resource){
	          		$user_follow = $table->getUserFollow($resource);
	          		foreach($user_follow as $row){
	          			if(in_array($row->user_id, $sent_follow)) continue;
	          			$sent_follow[] = $row->user_id; 
						$following = $viewer;
						$follower = Engine_Api::_()->user()->getUser($row->user_id);
						$notifyApi->addNotification($follower, $following, $story, 'story_follow');
	          		}
	          	}

				// Set photo
				if (!empty($_FILES['photo']) && $_FILES['photo']['tmp_name'] != "") {
					$album = $story->getSingletonAlbum();
					$params = array(
							// We can set them now since only one album is allowed
							'collection_id' => $album->getIdentity(),
							'album_id' => $album->getIdentity(),
							'story_id' => $story->getIdentity(),
							'user_id' => $viewer->getIdentity(),
					);
						
					$photoTable = Engine_Api::_()->getItemTable('story_photo');
					$photo = $photoTable->createRow();
					$photo->setFromArray($params);
					if(!empty($values['title'])){
						$photo->title = $values['title'];
					}
					$photo->save();
						
					$photo->setPhoto($_FILES['photo']);
					$uploading_photo = true;
						
					$story->photo_id = $photo->getIdentity();
					$story->save();
				} 
				
				//Check for multi photos
				if(isset($values['photo_description']) && $story){
					$album = $story->getSingletonAlbum();
					$params = array(
							// We can set them now since only one album is allowed
							'collection_id' => $album->getIdentity(),
							'album_id' => $album->getIdentity(),
							'story_id' => $story->getIdentity(),
							'user_id' => $viewer->getIdentity()
					);
					$count = count($values['photo_description']);
					if($count > 0){
						$i = 1; 
						for($i = 1; $i <= $count; $i++){
							$photo_input = "photo_" . $i;
							if (!empty($_FILES[$photo_input]) && $_FILES[$photo_input]['tmp_name'] != "") {
								
								
								$photoTable = Engine_Api::_()->getItemTable('story_photo');
								$photo = $photoTable->createRow();
								$photo->setFromArray($params);		
								if(!empty($values['photo_description'][$i-1])){
									$photo->title = $values['photo_title'][$i-1];
									$photo->description = $values['photo_description'][$i-1];
								}						
								$photo->save();								
								$photo->setPhoto($_FILES[$photo_input]);
								$uploading_photo = true;
								if($i == 1){
									$story->photo_id = $photo->getIdentity();
									$story->save();
								}						
								
							}
						}
					}
				}
				
					
				// Add tags
				$tags = preg_split('/[,]+/', $values['tags']);
				$tags = array_filter(array_map("trim", $tags));
				$story->tags()->addTagMaps($viewer, $tags);
					
				//Post Chapter
				$chapter_id = 0;
				if($story->allowChapters()){
					$chapterTable = Engine_Api::_()->getDbtable('chapters', 'story');
					$values['story_id'] = $story->getIdentity();
					$values['user_id'] = $viewer->getIdentity();
					$values['body'] = $values[$body];
					if(isset($values['chapter_title'])){
						$values['title'] = $values['chapter_title'];
					}
					if(isset($values['publish'])||isset($values['submit'])){
						$values['public'] = 1;	
					}
					if(isset($values['save'])){
						$values['public'] = 0;	
					}
					$last_chapter = $story->getLastChapter();
					if(!empty($last_chapter)){
						$values['chapter_id'] = $last_chapter->chapter_id;
						$chapter = $chapterTable->editChapter($values);
						if(isset($values['publish'])||isset($values['submit'])){
							$values['title'] = '';
							$values['body'] = '';
							$values['public'] = 0;
							unset($values['chapter_id']);
							$chapter = $chapterTable->addChapter($values);
						} 
					} else {
						$chapter = $chapterTable->addChapter($values);
						if($values['public'] == 1)
						{
							$values['title'] = '';
							$values['body'] = '';
							$values['public'] = 0;
							unset($values['chapter_id']);
							$chapter = $chapterTable->addChapter($values);
						}
					}
					
					// Add notification
					if(isset($values['publish'])||isset($values['submit'])){
						if($story->category_id==Story_Model_Category::STORY_THREAD){
							if($story->owner_id==$viewer->getIdentity()){
								$notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
								$members = $story->membership()->getMembers();
								foreach($members as $row){
									$poster = Engine_Api::_()->user()->getUser($row->user_id);
									$notifyApi->addNotification($poster, $viewer, $story, 'story_partner');
									break;
								}
							} else{
								$notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
								$poster = Engine_Api::_()->user()->getUser($story->owner_id);
								$notifyApi->addNotification($poster, $viewer, $story, 'story_partner');
							}
						}
					}
					$chapter_id = $chapter->getIdentity();
				}
					
				// $pending_photo = $story->getPhoto();
				// if($pending_photo && !empty($values['title'])){
				// 	$pending_photo->title = $values['title'];
				// 	$pending_photo->save();
				// }

				// CREATE AUTH STUFF HERE
				$auth = Engine_Api::_()->authorization()->context;
				$roles = array(
						'owner',
						'owner_member',
						'owner_member_member',
						'owner_network',
						'registered',
						'everyone');
					
				$auth_keys = array(
						'view' => 'everyone',
						'comment' => 'registered',
				);
					
				foreach ($auth_keys as $auth_key => $auth_default) {
					$auth_value = isset($values['auth_' . $auth_key]) ? $values['auth_' . $auth_key] :
					$auth_default;
					$authMax = array_search($auth_value, $roles);

					foreach ($roles as $i => $role) {
						$auth->setAllowed($story, $role, $auth_key, ($i <= $authMax));
					}
				}
					
				//Add activity only if story is published
				if ($story->isPublished()) {
					$action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer,
							$story, 'story_new');
					if ($action != null) {
						Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $story);
					}
				}
					
				// Commit
				$db->commit();
				if($uploading_photo && $story->category_id == Story_Model_Category::COMICS){
					//Just go back when COMIC Story
					return $this->_helper->redirector->gotoRoute(array('story_id' => $story->
							story_id, 'action' => 'create'), 'story_general', true);
				} 
				else if($story->category_id == Story_Model_Category::NOVEL) {
					if(isset($values['submit']))
					return $this->_helper->redirector->gotoRoute(array('story_id' => $story->
							story_id, 'action' => 'create'), 'story_general', true);
				} 
				else if($story->category_id == Story_Model_Category::STORY_THREAD) {
					//Invite friend
					$membershipTable = Engine_Api::_()->getDbtable('membership', 'story');
					if($membershipTable->getMembershipStory($story->story_id)==null)
					return $this->_helper->redirector->gotoRoute(array('story_id' => $story->
							story_id, 'action' => 'create', 'type' => 'invite', 'chapter_id' => $chapter_id), 'story_general', true);
				}

				
				//Return to manage Story
				return $this->_helper->redirector->gotoRoute(array('story_id' => $story->
						story_id, 'action' => 'manage'), 'story_general', true);
				

			}

			catch (exception $e) {
				$db->rollBack();
				throw $e;
			}
		} else {
			//Show not found if this  is not POST
			return $this->_forward('notfound');
		}
	}

	public function getCategoriesAction()
	{
		$category_id = $this->_getParam('category_id');
		$categories = Engine_Api::_()->getItemTable('story_category')->getChildrenOfParent($category_id);

		$ret = array();
		foreach($categories as $category){
			$ret[] = array('id' => $category->category_id,
					'name' => $category->category_name);
		}

		echo Zend_Json::encode($ret);
		die();
	}
	
	public function inviteAction(){
		if ($this->getRequest()->isPost()) {
			$values = $_POST;
			
			$story = Engine_Api::_()->getItem('story', $values['story_id']);
			if(!$story){
				return $this->_forward('requireauth', 'error', 'core');				
			}

			$friend = Engine_Api::_()->getItem('user', $values['friend_id']);
			if(!$friend){
				return $this->_forward('requireauth', 'error', 'core');
			}
			
			if($story->membership()->isMember($friend)){
				return $this->_forward('requireauth', 'error', 'core');
			}
			$story->membership()
			->addMember($friend)
			->setResourceApproved($friend);
			
			$memberInfo = $story->membership()
			->getMemberInfo($friend);
			$memberInfo->message = $values['message'];
			$memberInfo->save();

			// $story->invite_request = 1;
			$story->category_id = Story_Model_Category::STORY_THREAD;
			$story->save();
			
			Engine_Api::_()->getDbtable('notifications', 'activity')
			->addNotification($friend, $story->getOwner(), $story, 'story_request');
			
			return $this->_helper->redirector->gotoRoute(array('story_id' => $story->
						story_id, 'action' => 'manage'), 'story_general', true);
				
		}
	}

	
	public function requestStoryAction()
	{	
		$this->view->notification = $notification = $this->_getParam('notification');
		$object = $notification->getObject();
		if($object){
			$this->view->story_id = $object->getIdentity();
			$viewer = Engine_Api::_()->user()->getViewer();
			$memberInfo = $object->membership()
			->getMemberInfo($viewer);
			$this->view->message = $memberInfo->message;
			$this->view->redirect = $this->view->url(array('story_id' => $object->getIdentity()), 'story_create', true);
		} else {
			
		}
		
	}
	
	public function confirmAction()
	{
		if( !$this->_helper->requireUser()->isValid() ) return;
	
		// Get viewer and other user
		$viewer = Engine_Api::_()->user()->getViewer();
		
		
		$story_id = $this->_getParam('story_id');
		$story = Engine_Api::_()->getItem('story', $story_id);
		if(!$story){
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid Request');
			return;
		}
	
		// Make form
		$this->view->form = $form = new User_Form_Friends_Confirm();
	
		if( !$this->getRequest()->isPost() ) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('No action taken');
			return;
		}
	
		if( !$form->isValid($this->getRequest()->getPost()) ) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid data');
			return;
		}
	
		$friendship = $story->membership()->getRow($viewer);
		if( $friendship->active ) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Already accepted');
			return;
		}
	
		// Process
		$db = Engine_Api::_()->getDbtable('membership', 'story')->getAdapter();
		$db->beginTransaction();
	
		try {
			$story->membership()->setUserApproved($viewer);
	
			
			Engine_Api::_()->getDbtable('notifications', 'activity')
				->addNotification($story->getOwner(), $viewer, $story, 'story_accepted');
			
			//Clear flag Invite request
			// $prevChapter = $story->getLastChapterThread();
			// if(empty($prevChapter)) $story->invite_request = 1;
			// else $story->invite_request = 0;
			$story->save();
			
			$db->commit();	
			
			$notification = Engine_Api::_()->getDbtable('notifications', 'activity')
			->getNotificationBySubjectAndType($viewer, $story->getOwner(), 'story_request');
			if( $notification ) {
				$notification->mitigated = true;
				$notification->read = 1;
				$notification->save();
			}
			
			$message = "Your request has been processed successfully";
	
			$this->view->status = true;
			$this->view->message = $message;
			return $this->_forward('success', 'utility', 'core', array(
					'smoothboxClose' => true,
					'parentRefresh' => true,
					'messages' => array($message)
					//'You have accepted this friend request.'
	
			));
		} catch( Exception $e ) {
			$db->rollBack();
	
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('An error has occurred.');
			$this->view->exception = $e->__toString();
		}
	}
	
	public function rejectAction()
	{
		if( !$this->_helper->requireUser()->isValid() ) return;
	
		// Get viewer and other user
		$viewer = Engine_Api::_()->user()->getViewer();
		
		$story_id = $this->_getParam('story_id');
		$story = Engine_Api::_()->getItem('story', $story_id);
		if(!$story){
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid Request');
			return;
		}
	
		// Make form
		$this->view->form = $form = new User_Form_Friends_Reject();
	
		if( !$this->getRequest()->isPost() ) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('No action taken');
			return;
		}
	
		if( !$form->isValid($this->getRequest()->getPost()) ) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid data');
			return;
		}
	
		// Process
		$db = Engine_Api::_()->getDbtable('membership', 'user')->getAdapter();
		$db->beginTransaction();
	
		try {
			if ($story->membership()->isMember($viewer)) {
				$story->membership()->removeMember($viewer);
			}
	
			Engine_Api::_()->getDbtable('notifications', 'activity')
			->addNotification($story->getOwner(), $viewer, $story, 'story_cancelled');
			
			//Clear flag Invite request
			$story->category_id = Story_Model_Category::NOVEL;
			$story->invite_request = 0;
			$story->save();
	
			$db->commit();
			
			$notification = Engine_Api::_()->getDbtable('notifications', 'activity')
			->getNotificationBySubjectAndType($viewer, $story->getOwner(), 'story_request');
			if( $notification ) {
				$notification->mitigated = true;
				$notification->read = 1;
				$notification->save();
			}
	
			$message = Zend_Registry::get('Zend_Translate')->_('You ignored a story request from %s');
			$message = sprintf($message, $viewer->__toString());
	
			$this->view->status = true;
			$this->view->message = $message;
			return $this->_forward('success', 'utility', 'core', array(
					'smoothboxClose' => true,
					'parentRefresh' => true,
					'messages' => array($message),
			));
		} catch( Exception $e ) {
			$db->rollBack();
	
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('An error has occurred.');
			$this->view->exception = $e->__toString();
		}
	}
	
}
